<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属年级" prop="grade">
        <el-select filterable v-model="queryParams.grade" placeholder="请选择所属年级" clearable size="small">
          <el-option v-for="dict in grades" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属科目" prop="subject">
        <el-select filterable v-model="queryParams.subject" placeholder="请选择所属科目" clearable size="small">
          <el-option v-for="dict in subjects" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属年份" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入所属年份"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属学期" prop="semester">
        <el-select v-model="queryParams.semester" placeholder="请选择所属学期" clearable size="small">
          <el-option v-for="dict in semesters" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入资料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" @sort-change="sortChange">
      <el-table-column type="selection" width="55" align="center" />      
      <el-table-column label="所属地域" align="left" prop="region" width="120px"/>
      <el-table-column label="版本" align="left" prop="version" width="120px" sortable="custom"/>
      <el-table-column label="自定义合集" align="left" prop="collection" width="120px" sortable="custom"/>
      <el-table-column label="上传附件" align="left" prop="url">
        <template slot-scope="scope">
          <FileUploadPDF v-model="scope.row.url" :table="scope.row.id+':'+'material'+':'+'fj'"/>
        </template>
      </el-table-column>
      <el-table-column label="收费金额" align="center" prop="amount" width="100px" sortable="custom">
        <template slot-scope="scope">
          {{scope.row.isFree==1?'免费':'￥'+scope.row.amount}}
        </template>
      </el-table-column>
      <el-table-column label="分销折扣" align="center" prop="discount" width="100" sortable="custom"/>
      <el-table-column label="梯度比率" align="center" prop="discountBl" width="100" sortable="custom"/>
      <el-table-column label="浏览量" align="center" prop="readNum" width="90px" sortable="custom"/>
      <el-table-column label="下载量" align="center" prop="downNum" width="90px" sortable="custom"/>
      <el-table-column label="上传日期" align="center" prop="createTime" width="140" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传用户" align="center" prop="userId" :formatter="getUserName" width="120px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:info:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['system:info:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"            
            @click="creatQrCode(scope.row)"
            v-hasPermi="['system:info:edit']"
          >生成二维码</el-button>
        </template>
      </el-table-column>   
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <qrcodeD ref="qrcodeD" :dialogVisible="openQrCode" @cancelQr="cancelQr"></qrcodeD>
    <!-- 添加或修改资料信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入资料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属年级" prop="grade">
              <el-select filterable v-model="form.grade" placeholder="请选择所属年级" clearable style="width:100%;">
                <el-option v-for="dict in grades" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科目" prop="subject">
              <el-select filterable v-model="form.subject" placeholder="请选择所属科目" clearable style="width:100%;">
                <el-option v-for="dict in subjects" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属年份" prop="age">
              <el-input v-model="form.age" placeholder="请输入所属年份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属学期" prop="semester">
              <el-select v-model="form.semester" placeholder="请选择所属学期" clearable style="width:100%;">
                <el-option v-for="dict in semesters" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属地域" prop="region">
              <el-input v-model="form.region" placeholder="请输入所属地域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否免费" prop="isFree">
              <el-select v-model="form.isFree" placeholder="请选择是否免费" clearable style="width:100%;">
                <el-option v-for="dict in yesNo" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收费金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入收费金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="浏览量" prop="readNum">
              <el-input v-model="form.readNum" placeholder="请输入浏览量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分销折扣" prop="discount">
              <el-input v-model="form.discount" placeholder="请输入分销折扣" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="梯度比率" prop="discountBl">
              <el-input v-model="form.discountBl" placeholder="请输入梯度比率" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下载量" prop="downNum">
              <el-input v-model="form.downNum" placeholder="请输入下载量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传用户" prop="userId">
              <el-select filterable v-model="form.userId" placeholder="请选择上传用户" clearable style="width:100%;">
                <el-option v-for="dict in userList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="自定义合集" prop="collection">
              <el-input v-model="form.collection" placeholder="请输入自定义合集" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="800px" append-to-body :before-close="viewCancel">
      <div class="sketch_content">
        <div class="word-wrap" v-if="isWord==true" id="wordWrap">
          <div id="wordView" v-html="wordText"/>
        </div>
        <div id="pdf-container" v-else></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/business/info";
import { listUser } from "@/api/system/user";
import FileUploadPDF from '@/components/FileUploadPDF';
import { downLoadZip } from "@/utils/zipdownload";
import qrcodeD from "./qrcodeD";
import mammoth from "mammoth";
export default {
  name: "Info",
  components: {
    FileUploadPDF,
    qrcodeD
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资料信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      openQrCode: false,
      wordText: '',
      fileContent: '',
      isWord: false,
      grades: [],
      subjects: [],
      semesters: [],
      yesNo: [],
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        grade: null,
        subject: null,
        age: null,
        semester: null,
        materialName: null,
        region: null,
        url: null,
        isFree: null,
        amount: null,
        readNum: null,
        downNum: null,
        userId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: "资料名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts('grade').then(response => {
      this.grades = response.data;
    });
    this.getDicts('subject').then(response => {
      this.subjects = response.data;
    });
    this.getDicts('semester').then(response => {
      this.semesters = response.data;
    });
    this.getDicts('yes_no').then(response => {
      this.yesNo = response.data;
    });
    listUser().then(response => {
      this.userList = response.rows;
    });
  },
  methods: {
    getView(fileUrl) {
        fileUrl = fileUrl.toLowerCase();
        let index = fileUrl.lastIndexOf('.');
        if (fileUrl.substring(index)=='.pdf') {
          pdfjsLib.getDocument(fileUrl).promise.then(doc => {
            console.log('doc',doc);
            this.isWord = false;
            const pdfDoc = doc;
            const pageNumber = pdfDoc.numPages;
            for (let i=1; i<=pageNumber; i++) {
              pdfDoc.getPage(i).then(page => {
                const scale = 1;
                const viewport = page.getViewport({ scale: scale });
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;                
                document.getElementById('pdf-container').appendChild(canvas);
                const renderContext = {
                  canvasContext: context,
                  viewport: viewport
                };
                page.render(renderContext);
              });
            }
          });
        }else {
          const xhr = new XMLHttpRequest();
          xhr.open("get", fileUrl, true);
          xhr.responseType = "arraybuffer";
          xhr.onload = () => {
            if (xhr.status == 200) {
                this.isWord = true;
                mammoth.convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) }).then((resultObject) => {
                  console.log('resultObject',resultObject);
                  this.$nextTick(() => {
                      this.wordText = resultObject.value;
                  })
                })            
            }
          }
          xhr.send();
        }
    },
    getUserName(row) {
      for (let i in this.userList) {
        if (this.userList[i].userId === row.userId) {
          return this.userList[i].userName;
        }
      }
    },
    sortChange(column) {
      this.loading = true;
      if (column.prop === 'version') {
        this.queryParams.order = 'version';
      }else if (column.prop === 'collection') {
        this.queryParams.order = 'collection';
      }else if (column.prop === 'amount') {
        this.queryParams.order = 'amount';
      }else if (column.prop === 'readNum') {
        this.queryParams.order = 'read_num';
      }else if (column.prop === 'downNum') {
        this.queryParams.order = 'down_num';
      }else if (column.prop === 'createTime') {
        this.queryParams.order = 'create_time';
      }
      if (column.order === 'ascending') {
        this.queryParams.orderType = 'asc';
      } else if (column.order === 'descending') {
        this.queryParams.orderType = 'desc';
      }
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询资料信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    viewCancel() {
      if (document.getElementById("pdf-container")) {
        document.getElementById("pdf-container").innerHTML = '';
      }      
      this.viewOpen = false;
    },
    cancelQr() {
      this.openQrCode = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        grade: null,
        subject: null,
        age: null,
        semester: null,
        materialName: null,
        region: null,
        url: null,
        isFree: null,
        amount: null,
        readNum: null,
        downNum: null,
        userId: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资料信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.form.grade = this.form.grade+'';
        this.form.subject = this.form.subject+'';
        this.form.semester = this.form.semester+'';
        this.form.isFree = this.form.isFree+'';
        this.open = true;
        this.title = "修改资料信息";
      });
    },
    handleView(row) {
      var parent = document.getElementById("wordWrap");
      if (parent&&parent.firstChild) {
        document.getElementById("wordWrap").innerHTML = '<div id="wordView" v-html="wordText"/>';
      }      
      this.viewTitle = '浏览详情';
      this.getView(row.url);
      this.viewOpen = true;
    },
    creatQrCode(row) {
      let host = '';
      if (row.appId=='wxae0f0d0aef1a8645') {
        host = 'train.shudingkj.com';
      }else if (row.appId=='wx49c781286d16deea') {
        host = 'sell.shudingkj.com';
      }else if (row.appId=='wxff9cb9b0b37dfef8') {
        host = 'jkhmzw.shudingkj.com';
      }
      this.curPath = 'http://'+host+'/pages/material/detail/index?id='+row.id;
      this.$refs.qrcodeD.paths = this.curPath;
      this.openQrCode = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除资料信息编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const ids = this.ids;
      this.$confirm('是否确认导出选中的资料?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          downLoadZip('/system/info/export/'+ids, "资料");
        }).then(response => {
          this.download(response.msg);
        })
      /*this.download('system/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)*/
    }
  }
};
</script>
<style>
.word-wrap {
  padding: 15px;
  img {
    width: 100%;
  }
}
.sketch_content {
  overflow: auto;
  height: 750px;
  border-top: 1px solid #eff1f4;
  border-bottom: 1px solid #eff1f4;
  padding: 0px 30px 11px 27px;
}
.sketch_content::-webkit-scrollbar {
  width: 3px;
}
.sketch_content::-webkit-scrollbar-thumb {
  background: #8798AF;
  border-radius: 2px;
}
.sketch_content::-webkit-scrollbar-track {
  background: transparent;
}
</style>